package com.zjuh.taofood.biz.misc;

import java.text.ParseException;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class DumpDataScheduler implements ApplicationContextAware {
	
	private ApplicationContext applicationContext;
	
	private Scheduler scheduler;
	
	public DumpDataScheduler() {
		super();
	}
	
	private void addJob(Class<?> jobClass, String cronExpr) throws ParseException, SchedulerException {
		String jobName = jobClass.getSimpleName();
		JobDetail fullDumpDetail = new JobDetail(jobName, jobName + "Group", jobClass);
		CronTrigger fullDumpTrigger = new CronTrigger(jobName + "Trigger", jobName + "Group", cronExpr);
		scheduler.scheduleJob(fullDumpDetail, fullDumpTrigger);
	}

	public void init() throws SchedulerException, ParseException {
		scheduler = StdSchedulerFactory.getDefaultScheduler();
		scheduler.getContext().put("applicationContext", applicationContext);

		addJob(DumpDataJob.class, "0 0 1 * * ?");
		addJob(TopTopicJob.class, "0 0 2 * * ?");
		addJob(DumpRatesJob.class, "0 0 3 * * ?");
		
		try {
			scheduler.start();
		} catch (SchedulerException e) {
			throw new RuntimeException(e);
		}
	}
	
	public void close() {
		try {
			scheduler.shutdown();
		} catch (SchedulerException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

}
